
import 'package:camera/camera.dart';
import 'package:get/get.dart';

class CameraPageController extends GetxController {

  CameraController? _cameraController;
  late List<CameraDescription> _cameras;
  final _cameraControllerObs = Rx<CameraController?>(null);

  CameraController? get cameraController => _cameraControllerObs.value;

  final _cameraIndex = 0.obs;
  int get cameraIndex => _cameraIndex.value;
  set cameraIndex(int index)=>_cameraIndex.value = index;

  final _recording = false.obs;
  bool get recording => _recording.value;
  set recording (bool value) => _recording.value = value;

  void takePhotoAndUpload(){
    _cameraController?.takePicture();
  }
  Future<void> takeVideoAndUpload() async {
    if (!recording) {
      recording = true;
      _cameraController?.startVideoRecording();
    } else {
      recording = false;
      XFile? xFile = await _cameraController?.stopVideoRecording();
      print('flutter-video-path  = ${xFile}');
    }
  }

  void onSwitchFlash () {
    _cameraController?.setFlashMode(FlashMode.auto);
  }
  void onSwitchCamera () {
    if (_cameras.length > 1) {
      cameraIndex = cameraIndex == 0 ? 1:0;
      initCameraController();
    }
  }

  void initCameraController () async {
    _cameras = await availableCameras();
    // 2 选择具体的camera来创建camera controller
    _cameraController = CameraController(_cameras[0], ResolutionPreset.max);
    // 3 等待camera controller初始化
    _cameraController?.initialize().then((_) {
      _cameraControllerObs.value = _cameraController;
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            print('User denied camera access.');
            break;
          default:
            print('Handle other errors.');
            break;
        }
      }
    });

  }
}